// import { login, logout, getInfo } from '@/api/user'
import { login, singleLogin, getUsername } from '@/api/dashboard.js'
// import { loginDo } from '@/api/insideLink';
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from '@/store'
import { perdatagrid, getTxnOppoType } from '@/api/sys/seting'
import selectOptions from '@/utils/selectOptions.js'
import moment from 'moment'
import { getUrlParam } from '@/utils/common.js'
// import { getPublicKey } from '@/api/common';
const state = {
  token: getToken(),
  name: '',
  userId: '',
  userInfo: {},
  waringState: '',
  issuerRatingOptions: [
    {
      label: 'AAA',
      value: 'AAA',
      checked: false
    },
    {
      label: 'AA+',
      value: 'AA+',
      checked: false
    },
    {
      label: 'AA',
      value: 'AA',
      checked: false
    }
  ],
  bondTypeOptions: [
    {
      label: 'SCP',
      value: 'SCP',
      checked: false
    }, {
      label: 'CP',
      value: 'CP',
      checked: false
    }, {
      label: 'MTN',
      value: 'MTN',
      checked: false
    }, {
      label: 'PPN',
      value: 'PPN',
      checked: false
    }, {
      label: 'ABN',
      value: 'ABN',
      checked: false
    }, {
      label: '券商短融',
      value: '券商短融',
      checked: false
    }, {
      label: '商业银行债',
      value: '商业银行债',
      checked: false
    }, {
      label: '二级资本债',
      value: '二级资本债',
      checked: false
    }, {
      label: '企业债',
      value: '企业债',
      checked: false
    }, {
      label: '铁道债',
      value: '铁道债',
      checked: false
    }, {
      label: '非银次级债',
      value: '非银次级债',
      checked: false
    }, {
      label: '银行次级债',
      value: '银行次级债',
      checked: false
    }, {
      label: '非银金融债',
      value: '非银金融债',
      checked: false
    }
  ],
  investorType: [
    {
      label: '基金',
      value: '基金',
      checked: false
    }, {
      label: '券商',
      value: '券商',
      checked: false
    }, {
      label: '信托',
      value: '信托',
      checked: false
    }, {
      label: '保险',
      value: '保险',
      checked: false
    }, {
      label: '银行',
      value: '银行',
      checked: false
    }, {
      label: '其它',
      value: '其它',
      checked: false
    }
  ],
  person: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_WARINGSTATE: (state, waringState) => {
    state.waringState = waringState
  },
  SET_PERSON: (state, person) => {
    state.person = person
  },
  SET_ISSUERRATINGOPTIONS: (state, issuerRatingOptions) => {
    state.person = issuerRatingOptions
  },
  SET_BONDTYPEOPTIONS: (state, bondTypeOptions) => {
    state.person = bondTypeOptions
  }
}

const actions = {
  setWaring({ commit }, waringState) {
    return new Promise(resolve => {
      commit('SET_WARINGSTATE', waringState)
      resolve()
    })
  },
  getPerson({ commit }, person) {
    return new Promise(resolve => {
      perdatagrid().then(res => {
        const person = []
        res.results.forEach(item => {
          const obj = {
            value: item.chineseName,
            label: item.chineseName,
            checked: false
          }
          person.push(obj)
          selectOptions.person = person
          commit('SET_PERSON', person)
          resolve()
        })
      })
      getTxnOppoType().then(res => {
        // console.log('getTxnOppoType', res)
        // if (res && res.length > 0) {
        //   res.forEach(item => {
        //     item.label = item.TXN_OPPO_TYPE
        //     item.value = item.TXN_OPPO_TYPE
        //     item.checked = false
        //   })
        //   selectOptions.txnOppoType = res
        // }
      })
    })
  },
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password }).then(response => {
        if (response.success === true) {
        //   const { data, token } = response
          commit('SET_TOKEN', moment().format('YYYY-MM-DD HH:mm:ss'))
          setToken(moment().format('YYYY-MM-DD HH:mm:ss'))
          resolve(response)
        } else {
          resolve(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  singleLoginByToken({ commit, dispatch }, userInfo) {
    return new Promise((resolve, reject) => {
      const params = {
        userid: getUrlParam('userid'),
        Remote_addr: getUrlParam('Remote_addr'),
        SystemCode: getUrlParam('SystemCode'),
        md5key: getUrlParam('md5key')
      }
      console.log(params, 'params')
      singleLogin(params).then(res => {
        // tokentologin(data).then(res => {
        console.log(res, 'tokentologin')
        if (res.success) {
          commit('SET_TOKEN', moment().format('YYYY-MM-DD HH:mm:ss'))
          setToken(moment().format('YYYY-MM-DD HH:mm:ss'))
          // this.$router.push({ path: "/" });
          resolve(res)
        }
      }).catch(error => {
        reject(error, 'error-singleLogin')
      })
    })
  },
  getUsername({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUsername().then(res => {
        // console.log(res, 'getUsername')
        if (res != 'null') {
          commit('SET_NAME', res)
          resolve(res)
        } else {
          removeToken()
          resetRouter()
          reject('登录过期')
        }
      }).catch(error => {
        reject(error)
      })
    })
  }
  // user login
  // login({ commit }, userInfo) {
  //   const { username, password, phoneCode, phoneNo, phoneNoAreaCode, email, verifyType, emailCode, loginType, loginSource } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password, phoneCode, phoneNo, phoneNoAreaCode, email, verifyType, emailCode, loginType, loginSource: loginSource }).then(response => {
  //       if (response.code == 'ACK') {
  //         const { data, token } = response
  //         commit('SET_TOKEN', token)
  //         setToken(token)
  //         resolve(data)
  //       } else {
  //         resolve(response)
  //       }
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getPublicKey().then(res => {
  //       const publickKey = res.data
  //       commit('SET_PUBLICKEY', publickKey)
  //     })
  //     getInfo()
  //       .then(response => {
  //         const { data } = response
  //         console.log(data)
  //         if (!data) {
  //           reject('Verification failed, please Login again.')
  //         }
  //         const {
  //           roleType,
  //           loginName,
  //           id,
  //           permDetailDtoList,
  //           changeBaseInfoFlag
  //         } = data
  //         // roles must be a non-empty array
  //         if (!roleType || roleType == null) {
  //           reject('getInfo: roles must be a non-null array!')
  //         }
  //         // const roles = [roleType.code]
  //         // data.roles = ['admin']
  //         // commit('SET_ROLES', ['admin'])
  //         commit('SET_NAME', loginName)
  //         commit('SET_USERID', id)
  //         commit('SET_BASEINFOFLAG', changeBaseInfoFlag)
  //         commit('SET_USERINFO', data)
  //         commit('SET_IS_VISITOR', false)
  //         resolve(data)
  //       })
  //       .catch(error => {
  //         reject(error)
  //       })
  //   })
  // },
  // user logout
  // logout({ commit, state, dispatch }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token)
  //       .then(async() => {
  //         await router.push('/home')
  //         commit('SET_TOKEN', '')
  //         commit('SET_ROLES', [])
  //         commit('SET_NAME', '')
  //         commit('SET_USERID', '')
  //         commit('SET_BASEINFOFLAG', '')
  //         commit('SET_USERINFO', {})
  //         commit('SET_IS_VISITOR', false)
  //         removeToken()
  //         resetRouter()
  //         // Generate guest routes immediately after logging out
  //         const roles = ['visitors']
  //         const accessRoutes = await store.dispatch(
  //           'permission/generateVisitorRoutes',
  //           roles,
  //           { root: true }
  //         )
  //         router.addRoutes(accessRoutes)
  //         resolve()
  //       })
  //       .catch(error => {
  //         reject(error)
  //       })
  //   })
  // },
  // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     commit('SET_TOKEN', '')
  //     commit('SET_ROLES', [])
  //     commit('SET_IS_VISITOR', false)
  //     removeToken()
  //     resolve()
  //   })
  // },
  // dynamically modify permissions
  // async changeRoles({ commit, dispatch }, role) {
  //   const token = role + '-token';
  //   commit('SET_TOKEN', token)
  //   setToken(token)
  //   const { roles } = await dispatch('getInfo')
  //   resetRouter()
  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, {
  //     root: true
  //   })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)
  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
